package com.meteor.downloader.videodownloader.utils

import android.app.Activity
import android.app.WallpaperManager
import android.content.ActivityNotFoundException
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import com.meteor.downloader.videodownloader.R
import com.meteor.downloader.videodownloader.showToastIDMdm
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_APP_FROM_VALUE
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_AY_PERIOD_VALUE
import okio.IOException
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec

object MdmTotalUtils {
    fun playVideoMdm(context: Context, file: File?) {
        if (file == null) return
        val intent = Intent(Intent.ACTION_VIEW)
        val uri = FileProvider.getUriForFile(
            context, "${context.packageName}.fileprovider", file
        )
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(
            uri, when (file.extension) {
                "mp4", "MP4" -> {
                    "video/*"
                }

                "mp3", "MP3" -> {
                    "audio/*"
                }

                "jpg", "tiff", "jpeg", "webp", "png", "gif" -> {
                    "image/*"
                }

                else -> {
                    "video/*"
                }
            }
        )
        context.startActivity(intent)
    }

    fun shareVideoMdm(activity: Activity, file: File) {
        try {
            val uri = FileProvider.getUriForFile(
                activity, "${activity.packageName}.fileprovider", file
            )
            val shareIntent = Intent(Intent.ACTION_SEND).apply {
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                type = when (file.extension) {
                    "mp4", "MP4" -> {
                        "video/*"
                    }

                    "mp3", "MP3" -> {
                        "audio/*"
                    }

                    "jpg", "tiff", "jpeg", "webp", "png", "gif" -> {
                        "image/*"
                    }

                    else -> {
                        "video/*"
                    }
                }
                putExtra(Intent.EXTRA_STREAM, uri)
            }
            activity.startActivity(Intent.createChooser(shareIntent, ""))
        } catch (_: Exception) {
            activity.showToastIDMdm(R.string.mdm_sharing_failed)
        }
    }

    fun getFileDateMdm(long: Long): String {
        val sim = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault())
        return sim.format(Date(long))
    }

    fun fileNameMdm(fileName: String): Boolean {
        return !fileName.contains("/") && !fileName.contains("\u0000")
    }

    fun fileNameMdm2(fileName: String): Boolean {
        val illegalRegex = Regex("[\\\\/:*?\"<>|]")
        return !illegalRegex.containsMatchIn(fileName)
    }

    fun getClipTextMdm(board: ClipboardManager): String? {
        return try {
            val clip = board.primaryClip ?: return null
            if (clip.itemCount > 0) {
                clip.getItemAt(0).text.toString()
            } else {
                null
            }
        } catch (_: Exception) {
            null
        }
    }

    fun getMdmFullDate(long: Long): String {
        val sim = SimpleDateFormat("yyyy_MM_dd", Locale.getDefault())
        return sim.format(Date(long))
    }

    fun getMdmAppStatus(): Boolean {
        return DataManagerMdmUtils.getDataKeyMdm(MDM_AY_PERIOD_VALUE, "mdmValue") == "mdmValue"
                && DataManagerMdmUtils.getDataKeyMdm(MDM_APP_FROM_VALUE, "") == "mdmValue"
    }


    fun getClueForBitmap(context: Context, index: Int): Bitmap? {
        return try {
            val resourceId =
                context.resources.getIdentifier("meteor_${index}", "raw", context.packageName)
            getClueForBitmapTwo(context.resources.openRawResource(resourceId).readBytes())
        } catch (e: Exception) {
            null
        }
    }

    private fun getClueForBitmapTwo(bytes: ByteArray): Bitmap? {
        return try {
            val pasword = "mdmmeteordownloader"
            val key = "79fdsa7g9gh9u9r1".toByteArray()
            val newKey = getPasswordValue(pasword, key)
            val newBytes = getBitmapValue(bytes, newKey)
            return BitmapFactory.decodeByteArray(newBytes, 0, newBytes.size)
        } catch (e: Exception) {
            null
        }
    }

    private fun getPasswordValue(password: String, salt: ByteArray): SecretKey {
        val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
        val spec = PBEKeySpec(password.toCharArray(), salt, 65536, 256)
        val tmp = factory.generateSecret(spec)
        return SecretKeySpec(tmp.encoded, "AES")
    }

    private fun getBitmapValue(encryptedData: ByteArray, key: SecretKey): ByteArray {
        val iv = encryptedData.copyOfRange(0, 16)
        val actualData = encryptedData.copyOfRange(16, encryptedData.size)
        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
        return cipher.doFinal(actualData)
    }

    fun setWallpaperFromBitmap(
        context: Context,
        file: File,
        targetLockScreen: Boolean = false
    ) {
        val wm = WallpaperManager.getInstance(context)
        try {
            val bitmap = BitmapFactory.decodeFile(file.path)
            // 如果系统支持 FLAG（API 24+），可以精确设置到主屏/锁屏
            val flag = if (targetLockScreen)
                WallpaperManager.FLAG_LOCK else WallpaperManager.FLAG_SYSTEM
//            wm.setBitmap(bitmap, null, true, flag)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}